package com.kylin.module.study.business;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.kylin.common.Constants;
import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.FileOperater;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.module.study.forms.ArticleForm;
import com.kylin.module.study.orm.Article;

public class ArticleBlogic {

	protected static Logger log = Logger.getLogger(ArticleBlogic.class);

	/**
	 * 添加学习文章
	 * 
	 * @param form
	 */
	public void addArticle(ArticleForm form) throws BusinessException {
		log.debug("插入新的文章 ：" + form.getTitle());
		Article obj = new Article();
		obj.setActive(new Short("1"));
		//上传声音文件
		if(form.getAudio()!=null && form.getAudio().getFileSize() > 0){
			String audioPath = StudyBlogic.uploadMedia(Constants.MEDIA_ARTICLE, form.getAudio(), null);
		    obj.setAudio(audioPath);
		}
		obj.setCatarticle(new Dict(form.getCatarticleid()));
		obj.setCreatedon(new Date());
		obj.setLanguage(form.getLanguage());
		obj.setTargetlang(form.getTargetlang());
		obj.setOrdering(form.getOrdering());
		obj.setTitle(form.getTitle());
		obj.setContent(form.getContent());
		BaseHibernateDAO.save(obj);
	}

	/**
	 * 修改学习文章
	 * 
	 * @param form
	 */
	public Article updateArticle(ArticleForm form) throws BusinessException {
		log.debug("修改文章 ：" + form.getTitle());
		Article obj = (Article) BaseHibernateDAO.findById(Article.class, form.getId());
		//上传 修改 声音文件
		if(form.getAudio()!=null 
				&& !form.getAudio().getFileName().equals("") 
				&& form.getAudio().getFileSize() > 0){
			String audioPath = StudyBlogic.uploadMedia(Constants.MEDIA_ARTICLE, form.getAudio(), obj.getAudio());
		    obj.setAudio(audioPath);
		}
		obj.setCatarticle(new Dict(form.getCatarticleid()));
		obj.setLastupdatedon(new Date());//最后修改时间
		obj.setTitle(form.getTitle());
		obj.setContent(form.getContent());
		BaseHibernateDAO.update(obj);
		return obj;
	}

	/**
	 * 根据ID获得学习文章
	 * 
	 * @param id
	 */
	public Article getArticleById(Long id) throws BusinessException {
		return (Article) BaseHibernateDAO.findById(Article.class, id);
	}

	/**
	 * 根据ID删除文章
	 * 
	 * @param id
	 */
	public void deleteById(Long id) throws BusinessException {
		Article obj = getArticleById(id);
		if (obj != null) {
			BaseHibernateDAO.delete(obj);
			try {
				FileOperater.deleteFile(Constants.MEDIA_ARTICLE, obj.getAudio());
			} catch (IOException e) {
				e.printStackTrace();
				throw new BusinessException("删除文章附属声音文件失败："+Constants.MEDIA_ARTICLE +File.separator+ obj.getAudio());
			}
		}
	}
	
	public List getArticleByCat(Long catId) throws BusinessException
	{
		return BaseHibernateDAO.findByProperty(Article.class,"catarticle",new Dict(catId));
	}

}
